package com.markus.code.剑指offer;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/31 13:27
 * todo: 矩阵中的路径
 */
public class PathExist {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        char[] chars = word.toCharArray();
        boolean[] visited = new boolean[board.length * board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (process(board, board[i].length, board.length, j, i, chars, 0, visited)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean process(char[][] board, int cols, int rows, int col, int row, char[] words, int index, boolean[] visited) {
        if (index == words.length) {
            return true;
        }
        if (col < 0 || col >= cols || row < 0 || row >= rows || visited[row * cols + col]) {
            return false;
        }
        if (words[index] != board[row][col]) {
            return false;
        }
        visited[row * cols + col] = true;
        boolean res = process(board, cols, rows, col + 1, row, words, index + 1, visited) ||
                process(board, cols, rows, col - 1, row, words, index + 1, visited) ||
                process(board, cols, rows, col, row + 1, words, index + 1, visited) ||
                process(board, cols, rows, col, row - 1, words, index + 1, visited);
        visited[row * cols + col] = false;
        return res;
    }

    public static void main(String[] args) {
        char[][] board = {{'C', 'A', 'A'}, {'A', 'A', 'A'}, {'B', 'C', 'D'}};
        String word = "AAB";
        PathExist demo = new PathExist();
        System.out.println(demo.exist(board, word));
    }
}
